package com.erlin.common.api;

import com.erlin.common.api.param.WxRegisterParam;
import com.erlin.common.client.WxClient;
import com.erlin.common.config.properties.WxProperties;
import com.erlin.common.exception.ElException;
import com.erlin.common.security.config.TokenProperties;
import com.erlin.common.utils.JwtTokenUtils;
import com.erlin.platform.service.IElUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "用户登录相关")
@RequestMapping("/api/auth")
@Slf4j
public class AuthController {
    @Autowired
    private TokenProperties tokenProperties;
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    private IElUserService elUserService;
    @Autowired
    private WxClient wxClient;
    @Autowired
    private WxProperties wxProperties;

    @ApiOperation("登录授权")
    @PostMapping(value = "/login")
    public Map<String, String> login(HttpServletResponse response, String user, String password) {
        String token = elUserService.login(user, password);
        if (StringUtils.isEmpty(token)) {
            throw new ElException("用户名或密码错误");
        }
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("token", token);
        resultMap.put("tokenHead", tokenProperties.getTokenStartWith());
        response.setHeader("Authorization", tokenProperties.getTokenStartWith() + " " + token);
        return resultMap;
    }

    @ApiOperation("微信登录")
    @PostMapping("/wxLogin")
    public UserInfoVo wxLogin(@NotBlank String code, HttpServletResponse response) {
        UserInfoVo userInfoVo = elUserService.wxLogin(code);
        response.setHeader(tokenProperties.getAuthName(), tokenProperties.getHeader(userInfoVo.getToken()));
        return userInfoVo;
    }

    @ApiOperation("微信用户注册")
    @PostMapping("/wxRegister")
    public UserInfoVo wxRegister(@Validated @RequestBody WxRegisterParam param,HttpServletResponse response){
        UserInfoVo userInfoVo = elUserService.wxRegister(param);
        response.setHeader(tokenProperties.getAuthName(), tokenProperties.getHeader(userInfoVo.getToken()));
        return userInfoVo;
    }
}
